package logic

import (
	"context"
	"strconv"
	"week2_zg6/common/es"
	"week2_zg6/common/mysql"

	"week2_zg6/bookRpc/book"
	"week2_zg6/bookRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type DataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DataLogic {
	return &DataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DataLogic) Data(in *book.DataRequest) (*book.DataResponse, error) {
	var str []mysql.Book
	err := mysql.DB.Model(&mysql.Book{}).Find(&str).Error
	if err != nil {
		return nil, err
	}
	for _, v := range str {
		_, err = es.Client.Index().
			Index("book").
			Id(strconv.Itoa(int(v.ID))).
			BodyJson(v).
			Do(context.Background())
		if err != nil {
			return nil, err
		}
	}
	return &book.DataResponse{
		Date: "数据同步成功",
	}, nil
}
